package org.jeecg.modules.demo.weixin.smtoncecardusers.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.demo.weixin.entity.SmtOnceCardUsers;
import org.jeecg.modules.demo.weixin.smtoncecardusers.service.ISmtOnceCardUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Description: 用户次卡表
 * @Author: jeecg-boot
 * @Date: 2023-10-28
 * @Version: V1.0
 */
@Api(tags = "用户次卡表")
@RestController
@RequestMapping("/weixin/smtoncecardusers/smtOnceCardUsers")
@Slf4j
public class SmtOnceCardUsersController extends JeecgController<SmtOnceCardUsers, ISmtOnceCardUsersService> {
    @Autowired
    private ISmtOnceCardUsersService smtOnceCardUsersService;

    /**
     * 分页列表查询
     *
     * @param smtOnceCardUsers
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @ApiOperation(value = "smt_once_card_users-分页列表查询", notes = "smt_once_card_users-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SmtOnceCardUsers>> queryPageList(SmtOnceCardUsers smtOnceCardUsers,
                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                         HttpServletRequest req) {
        QueryWrapper<SmtOnceCardUsers> queryWrapper = QueryGenerator.initQueryWrapper(smtOnceCardUsers, req.getParameterMap());
        Page<SmtOnceCardUsers> page = new Page<SmtOnceCardUsers>(pageNo, pageSize);
        IPage<SmtOnceCardUsers> pageList = smtOnceCardUsersService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param smtOnceCardUsers
     * @return
     */
    @AutoLog(value = "smt_once_card_users-添加")
    @ApiOperation(value = "smt_once_card_users-添加", notes = "smt_once_card_users-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SmtOnceCardUsers smtOnceCardUsers) {
        smtOnceCardUsersService.save(smtOnceCardUsers);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param smtOnceCardUsers
     * @return
     */
    @AutoLog(value = "smt_once_card_users-编辑")
    @ApiOperation(value = "smt_once_card_users-编辑", notes = "smt_once_card_users-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SmtOnceCardUsers smtOnceCardUsers) {
        smtOnceCardUsersService.updateById(smtOnceCardUsers);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "smt_once_card_users-通过id删除")
    @ApiOperation(value = "smt_once_card_users-通过id删除", notes = "smt_once_card_users-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        smtOnceCardUsersService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "smt_once_card_users-批量删除")
    @ApiOperation(value = "smt_once_card_users-批量删除", notes = "smt_once_card_users-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.smtOnceCardUsersService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "smt_once_card_users-通过id查询")
    @ApiOperation(value = "smt_once_card_users-通过id查询", notes = "smt_once_card_users-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SmtOnceCardUsers> queryById(@RequestParam(name = "id", required = true) Integer id) {
        SmtOnceCardUsers smtOnceCardUsers = smtOnceCardUsersService.getById(id);
        if (smtOnceCardUsers == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(smtOnceCardUsers);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param smtOnceCardUsers
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SmtOnceCardUsers smtOnceCardUsers) {
        return super.exportXls(request, smtOnceCardUsers, SmtOnceCardUsers.class, "smt_once_card_users");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SmtOnceCardUsers.class);
    }


    /**
     * 查询每个用户的已有计次项目
     *
     * @return
     */
    @SneakyThrows
    @GetMapping(value = "/queryCount")
    public Integer queryCount(@RequestParam("uid") Integer uid, @RequestParam String merId) throws ParseException {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        QueryWrapper<SmtOnceCardUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", uid);
        queryWrapper.gt("card_rest", 0);
        queryWrapper.eq("merchant_id", Integer.valueOf(merId));
//        queryWrapper.and(cardQueryWrapper -> cardQueryWrapper.in("card_valid_date", "无限制").or().apply("merchant_id", payOrder.getMerId()));
        List<SmtOnceCardUsers> usersList = smtOnceCardUsersService.list(queryWrapper);
        if (CollectionUtils.isEmpty(usersList)) {
            return null;
        }
        List<SmtOnceCardUsers> counts = new ArrayList<>();
        Stream<SmtOnceCardUsers> smtOnceCardUsersStream = usersList.stream().filter(smtOnceCardUsers1 ->
                smtOnceCardUsers1.getCardValidDate().equals("无限制")
        );
        if (smtOnceCardUsersStream != null) {
            List<SmtOnceCardUsers> smtOnceCardUsers = smtOnceCardUsersStream.collect(Collectors.toList());
            counts.addAll(smtOnceCardUsers);
        }
        usersList.forEach(card -> {
            if (!card.getCardValidDate().equals("无限制")) {
                if (LocalDate.parse(card.getCardValidDate(), dateTimeFormatter).compareTo(LocalDate.now()) > 0) {
                    counts.add(card);
                }
            }
        });
        return counts.size();
    }


}
